package com.example.esp8266;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.lifecycle.ViewModelProvider;

import com.example.esp8266.databinding.ActivityMainBinding;
import com.google.gson.Gson;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Arrays;
import java.util.Optional;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private final Gson gson = new Gson();
    private final String BOTTOM_SHEET_FRAGMENT = "bottomSheetFragmentTag";
    private final EventAdapter2 adapter = new EventAdapter2();
    private MainViewModel mainViewModel;

    private SettingBottomFragment fragment;
    private long settingCurrentTime = System.currentTimeMillis();

    private String currentClipboardStr = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        fragment = new SettingBottomFragment();

        mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);

        binding.tool.setNavigationOnClickListener(v -> binding.drawer.openDrawer(GravityCompat.START));
        binding.drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {

            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        binding.name.setOnClickListener(v -> {
            if (System.currentTimeMillis() - settingCurrentTime < 1000) {//手抖快速点击导致崩溃
                settingCurrentTime = System.currentTimeMillis();
                return;
            }
            fragment.show(getSupportFragmentManager(), BOTTOM_SHEET_FRAGMENT);
        });

        binding.list.setAdapter(adapter);
        binding.navi.setNavigationItemSelectedListener(item -> {
            if (item.getItemId() == R.id.about) {
                startActivity(new Intent(MainActivity.this, AboutActivity.class));
            }
            return false;
        });
        binding.item1.setSwitchListener((buttonView, isChecked) -> mainViewModel.sendMsg(gson.toJson(isChecked ? LiteDao.enableLed() : LiteDao.disableLed())));

        mainViewModel.paramsWrapper.observe(this, wrapper -> {
            if (wrapper == null) return;
            if (!wrapper.isEmpty()) {
                binding.name.setText(String.valueOf(wrapper.getDeviceName()));
                mainViewModel.initMqttUtil(wrapper);
                mainViewModel.setCallback(callback);
                mainViewModel.setListener(listener);
                mainViewModel.startConnect();
            } else {
                Toast.makeText(MainActivity.this, "空配置", Toast.LENGTH_SHORT).show();
            }
        });
        mainViewModel.loadLocalMqttParams(getSharedPreferences("阿巴阿巴", MODE_PRIVATE));

    }

    private final MqttCallback callback = new MqttCallback() {
        @Override
        public void connectionLost(Throwable throwable) {
            runOnUiThread(() -> adapter.add("断开连接"));
        }

        @Override
        public void messageArrived(String s, MqttMessage mqttMessage) {
            runOnUiThread(() -> {
                String data = new String(mqttMessage.getPayload());
                adapter.add("收到数据：" + data);
                Response response = gson.fromJson(data, Response.class);
                Optional.ofNullable(response)
                        .map(Response::getItems)
                        .ifPresent(itemsDTO -> {
                            Optional.ofNullable(itemsDTO.getHumi())
                                    .ifPresent(humiDTO -> binding.wast.setText(String.valueOf(humiDTO.getValue())));
                            Optional.ofNullable(itemsDTO.getTemp())
                                    .ifPresent(tempDTO -> binding.temp.setText(String.valueOf(tempDTO.getValue())));
                            Optional.ofNullable(itemsDTO.getLed())
                                    .ifPresent(ledDTO -> binding.item1.setEnable(ledDTO.getValue() > 0));
                        });
            });
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            runOnUiThread(() -> adapter.add("消息发送完成：" + Arrays.toString(iMqttDeliveryToken.getTopics())));
        }
    };

    private final MqttUtilConnectListener listener = new MqttUtilConnectListener() {

        @Override
        public void onConnectSuccess(MqttClient client, MqttConnectUtil mqttConnectUtil) {
            adapter.add("连接成功");
            mqttConnectUtil.subscribeTopic();
        }

        @Override
        public void onConnectFailure(Exception e) {
            adapter.add("连接失败");
        }
    };

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            String clipboardContent = getClipboardContent(this);
            if (TextUtils.isEmpty(clipboardContent)) return;
            if (TextUtils.equals(clipboardContent,currentClipboardStr)) return;
            currentClipboardStr = clipboardContent;

            AliyunClipboardBean aliyunClipboardBean = null;
            try {
                aliyunClipboardBean = gson.fromJson(clipboardContent, AliyunClipboardBean.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (aliyunClipboardBean == null) return;
            MqttParamsWrapper transform = aliyunClipboardBean.transform();
            MqttParamsWrapper value = mainViewModel.paramsWrapper.getValue();
            if (value != null){
                if (value.equals(transform)) {
                    return;
                }
            }
            new AlertDialog.Builder(this)
                    .setTitle("连接参数设置！")
                    .setMessage("已从您的剪切板获取参数，是否使用此参数进行连接？")
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .setPositiveButton("确定", (dialog, which) -> {
                        fragment.show(MainActivity.this.getSupportFragmentManager(), BOTTOM_SHEET_FRAGMENT);
                        mainViewModel.paramsWrapper.postValue(transform);
                        dialog.dismiss();
                    })
                    .create()
                    .show();
        }
    }

    /**
     * 获取剪切板上的内容
     */
    @Nullable
    public static String getClipboardContent(Context context) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm != null) {
            ClipData data = cm.getPrimaryClip();
            if (data != null && data.getItemCount() > 0) {
                ClipData.Item item = data.getItemAt(0);
                if (item != null) {
                    CharSequence sequence = item.coerceToText(context);
                    if (sequence != null) {
                        return sequence.toString();
                    }
                }
            }
        }
        return null;
    }

}